# ArchLinux:
# Maintainer: Gustavo Alvarez <sl1pkn07@gmail.com>
# Contributor: Mikhail Vorozhtsov <mikhail.vorozhtsov@gmail.com>
# Contributor: Nagisa <simonas@kazlauskas.me>
# Contributor: Misc <andreas.reis@gmail.com>
# Contributor: Jeagoss <jgoliver@jeago.com>
# MSYS2:
# Maintainer: Ray Donnelly <mingw.android@gmail.com>

_realname=chromium-dev

#########################
## -- Build options -- ##
#########################
_use_clang=0   # Use clang compiler. Results in faster build and smaller chromium.
_use_pax=0     # If set 1, change PaX permisions in executables NOTE: only use if use PaX environment (IN TEST)

##############################################
## -- Package and components information -- ##
##############################################
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=41.0.2224.3
pkgrel=1
pkgdesc='The open-source project behind Google Chrome (Dev Channel) (mingw-w64)'
arch=('i686' 'x86_64')
url="https://www.chromium.org/"
license=('BSD')
depends=("${MINGW_PACKAGE_PREFIX}-hicolor-icon-theme"
         "${MINGW_PACKAGE_PREFIX}-gtk2"
         "${MINGW_PACKAGE_PREFIX}-icu"
         "${MINGW_PACKAGE_PREFIX}-libexif"
         "${MINGW_PACKAGE_PREFIX}-libwebp"
         "${MINGW_PACKAGE_PREFIX}-libxslt"
         "${MINGW_PACKAGE_PREFIX}-nss"
         "${MINGW_PACKAGE_PREFIX}-snappy"
         "${MINGW_PACKAGE_PREFIX}-speex"
         )
#         "${MINGW_PACKAGE_PREFIX}-minizip"
#         "${MINGW_PACKAGE_PREFIX}-re2"
#         "${MINGW_PACKAGE_PREFIX}-speech-dispatcher"
#         "${MINGW_PACKAGE_PREFIX}-ttf-font"

makedepends=(
#             'elfutils'
             'gperf'
             "${MINGW_PACKAGE_PREFIX}-ninja"
             "${MINGW_PACKAGE_PREFIX}-python2-jinja"
             'subversion'
             'yasm'
             'git'
             'depot-tools-git')
#             'perl-json'
#             'python2-beautifulsoup3'
#             'python2-simplejson'
#             'python2-ply'
optdepends=('chromium-pepper-flash-dev: PPAPI Flash Player (Dev Channel)'
            'kdebase-kdialog: needed for file dialogs in KDE'
            'gnome-keyring: for storing passwords in GNOME keyring'
            'libgnome-keyring: for storing passwords in GNOME keyring'
            'kdeutils-kwalletmanager: for storing passwords in KWallet')
provides=('chromium-dev' 'chromedriver')
[ "${CARCH}" = "x86_64" ] && makedepends+=('lib32-gcc-libs' 'lib32-zlib') && warning "To build need active [multilib] repository, if not , fail build"
install=chromium-dev.install
_source="chromium-${pkgver}.tar.xz"
backup=('etc/chromium-dev/default')
source=("https://commondatastorage.googleapis.com/chromium-browser-official/${_source}"
        'chromium-dev.desktop'
        'chromium-dev.sh'
        'chromium-dev.default'
        'chromium-dev.xml'
        # Patch form Gentoo
        'https://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-x86/www-client/chromium/files/chromium-system-jinja-r7.patch'
        # Misc Patches

        # Patch from crbug (chromium bugtracker)
        )
sha256sums=("$(curl -sL "https://commondatastorage.googleapis.com/chromium-browser-official/${_source}.hashes" | grep sha256 | cut -d " " -f3)"
            'bfc4b4f1600e1a3d8d67992548f8e69c3c81e3a5131eae764a4c631baa4391c5'
            '026bd188d83ae04164219d7ca2eefd818388dedc24b1cd6d84e60cb23df99b79'
            '89b342c9bcfc7bdd26adf7958b9217ce6cf1dfb39a80ec532987614625732fad'
            '25b123bb10d78afb1889bd9e3198c57968fa8f1da502b116e7df58d3e3bacaf5'
            # Patch form Gentoo
            'ff06a869615dd10ed3b26946b6a3113b3866c4d72183037be30996857e56ce32'
            # Misc Patches

            # Patch from crbug (chromium bugtracker)
            )
options=('!strip')
noextract=("${_source}")

# Google API keys (see https://www.chromium.org/developers/how-tos/api-keys)
# Note: These are for Arch Linux use ONLY. For your own distribution, please
# get your own set of keys. Feel free to contact foutrelis@archlinux.org for
# more information.
_google_api_key="AIzaSyDwr302FpOSkGRpLlUpPThNTDPbXcIn_FM"
_google_default_client_id="413772536636.apps.googleusercontent.com"
_google_default_client_secret="0ZChLK6AxeA3Isu96MkwqDR4"

################################################
## -- Don't touch anything below this line -- ##
################################################

[ "${CARCH}" = "i686" ] && _target_arch="ia32" && _arch="x86_32"
[ "${CARCH}" = "x86_64" ] && _target_arch="x64" && _arch="x86_64"

# If use PaX environment, need 'paxctl'
[ "${_use_pax}" = "1" ] && makedepends+=('paxctl')

if [ "${_use_clang}" = "1" ]; then
  makedepends+=('clang')
fi

# Are we in Gnome?
_use_gnome=0
if [ -f /usr/lib/libgnome-keyring.so ]; then
  depends+=('libgnome-keyring')
  _use_gnome=1
fi

# Use Pulseaudio?
_use_pulseaudio=0
if [ -x /usr/bin/pulseaudio ]; then
  _use_pulseaudio=1
fi

prepare() {
  ##############################
  ## -- Get ready to build -- ##
  ##############################

  # Clean environment
  for i in $(find . -maxdepth 1 -type d -name 'chromium*' -o -name 'python-path'); do rm -fr ${i}; done

  # Uncompress sources
  cd ${srcdir}
  tar -xf "${srcdir}"/${_source} || true
  # Set Python2 path
  mkdir -p python-path
  ln -s /usr/bin/python2 "${srcdir}/python-path/python"
  export PATH="${srcdir}/python-path:$PATH"

  cd "chromium-${pkgver}"

  msg2 "Make sure use Python 2"
  find . -type f -exec sed -i -r \
    -e 's|/usr/bin/python$|&2|g' \
    -e 's|(/usr/bin/python2)\.4$|\1|g' \
    {} +

  msg2 "Fix to save configuration in ~/.config/chromium-dev"
  sed -e "s|'filename': 'chromium-browser'|'filename': 'chromium-dev'|" \
      -e "s|'confdir': 'chromium'|'confdir': 'chromium-dev'|" \
      -i chrome/chrome_exe.gypi
  sed -e 's|config_dir.Append("chromium")|config_dir.Append("chromium-dev")|' \
      -e 's|config_dir.Append("chrome-frame")|config_dir.Append("chrome-frame-dev")|' \
      -i chrome/common/chrome_paths_linux.cc

  msg2 "Patch Sources"
  # Patch sources from Gentoo
  patch -p0 -i ../chromium-system-jinja-r7.patch

  # Patch from crbug (chromium bugtracker)

  # Misc Patches:

  # Make it possible to remove third_party/adobe
  echo > "${srcdir}/flapper_version.h"

  msg2 "Remove unnecessary components to save space"
  # Remove most bundled libraries. Some are still needed.
  build/linux/unbundle/remove_bundled_libraries.py \
	'base/third_party/dmg_fp' \
	'base/third_party/dynamic_annotations' \
	'base/third_party/icu' \
	'base/third_party/nspr' \
	'base/third_party/superfasthash' \
	'base/third_party/symbolize' \
	'base/third_party/valgrind' \
	'base/third_party/xdg_mime' \
	'base/third_party/xdg_user_dirs' \
	'breakpad/src/third_party/curl' \
	'chrome/third_party/mozilla_security_manager' \
	'courgette/third_party' \
	'crypto/third_party/nss' \
	'native_client/src/third_party/dlmalloc' \
	'net/third_party/mozilla_security_manager' \
	'net/third_party/nss' \
	'third_party/WebKit' \
	'third_party/angle' \
	'third_party/angle/src/third_party/compiler' \
	'third_party/brotli' \
	'third_party/cacheinvalidation' \
	'third_party/cld_2' \
	'third_party/cros_system_api' \
	'third_party/cython/python_flags.py' \
	'third_party/dom_distiller_js' \
	'third_party/dom_distiller_js/package/proto_gen/third_party/dom_distiller_js' \
	'third_party/ffmpeg' \
	'third_party/fips181' \
	'third_party/flot' \
	'third_party/google_input_tools' \
	'third_party/google_input_tools/third_party/closure_library' \
	'third_party/google_input_tools/third_party/closure_library/third_party/closure' \
	'third_party/hunspell' \
	'third_party/iccjpeg' \
	'third_party/jsoncpp' \
	'third_party/jstemplate' \
	'third_party/khronos' \
	'third_party/leveldatabase' \
	'third_party/libaddressinput' \
	'third_party/libevent' \
	'third_party/libjingle' \
	'third_party/libphonenumber' \
	'third_party/libsrtp' \
	'third_party/libusb' \
	'third_party/libvpx' \
	'third_party/libvpx/source/libvpx/third_party/x86inc' \
	'third_party/libwebm' \
	'third_party/libxml/chromium' \
	'third_party/libXNVCtrl' \
	'third_party/libyuv' \
	'third_party/lss' \
	'third_party/lzma_sdk' \
	'third_party/mesa' \
	'third_party/modp_b64' \
	'third_party/mt19937ar' \
	'third_party/npapi' \
	'third_party/openmax_dl' \
	'third_party/opus' \
	'third_party/ots' \
	'third_party/protobuf' \
	'third_party/pdfium' \
	'third_party/pdfium/third_party/logging.h' \
	'third_party/pdfium/third_party/macros.h' \
	'third_party/pdfium/third_party/numerics' \
	'third_party/pdfium/third_party/template_util.h' \
	'third_party/polymer' \
	'third_party/qcms' \
	'third_party/readability' \
	'third_party/sfntly' \
	'third_party/skia' \
	'third_party/smhasher' \
	'third_party/sqlite' \
	'third_party/tcmalloc' \
	'third_party/tlslite' \
	'third_party/trace-viewer' \
	'third_party/trace-viewer/third_party/d3' \
	'third_party/trace-viewer/third_party/components/polymer' \
	'third_party/trace-viewer/third_party/gl-matrix' \
	'third_party/trace-viewer/third_party/jszip' \
	'third_party/trace-viewer/third_party/tvcm' \
	'third_party/trace-viewer/third_party/tvcm/third_party/beautifulsoup/polymer_soup.py' \
	'third_party/undoview' \
	'third_party/usrsctp' \
	'third_party/webdriver' \
	'third_party/webrtc' \
	'third_party/widevine' \
	'third_party/x86inc' \
	'third_party/zlib/google' \
	'url/third_party/mozilla' \
	'v8/src/third_party/fdlibm' \
	'v8/src/third_party/kernel' \
	'v8/src/third_party/valgrind' \
	--do-remove



  msg2 "Setup NaCl/PNaCl SDK: Download and install NaCl/PNaCl toolchains"
  build/download_nacl_toolchains.py --packages nacl_x86_newlib,pnacl_newlib,pnacl_translator

}

build() {
  cd "chromium-${pkgver}"

  #######################
  ## -- Let's build -- ##
  #######################
  msg2 "Building Chromium..."

  if [ "${_use_clang}" = "0" ]; then
    # Silence "typedef 'x' locally defined but not used" warnings
    CFLAGS+=' -Wno-unused-local-typedefs'
  elif [ "${_use_clang}" = "1" ]; then
    sed "s|'-Wno-unused-local-typedef'|#'-Wno-unused-local-typedef'|g" -i build/common.gypi
  fi

  # NOTES:
  # -Denable_sql_database=0                    | https://crbug.com/22208
  # -Dlogging_like_official_build=1            | Save space by removing DLOG and DCHECK messages (about 6% reduction).
  # -Dlinux_use_gold_flags=0                   | Never use bundled gold binary. Disable gold linker flags for now.
  # -Dusb_ids_path=/usr/share/hwdata/usb.ids   | Use the file at run time instead of effectively compiling it in.

  local _flags=(
    -Ddisable_glibc=1
    -Ddisable_fatal_linker_warnings=1
    -Dffmpeg_branding=Chrome
    -Dflapper_version_h_file="${srcdir}/flapper_version.h"
    -Dgoogle_api_key="${_google_api_key}"
    -Dgoogle_default_client_id="${_google_default_client_id}"
    -Dgoogle_default_client_secret="${_google_default_client_secret}"
    -Dicu_use_data_file_flag=0
    -Dlibspeechd_h_prefix=speech-dispatcher/
    -Dlinux_link_gnome_keyring="${_use_gnome}"
    -Dlinux_link_gsettings="${_use_gnome}"
    -Dlinux_link_libpci=1
    -Dlinux_link_libspeechd=1
    -Dlinux_link_pulseaudio="${_use_pulseaudio}"
    -Dlinux_strip_binary=1
    -Dlinux_use_bundled_binutils=0
    -Dlinux_use_bundled_gold=0
    -Dlinux_use_gold_flags=0
    -Dlogging_like_official_build=1
    -Dno_strict_aliasing=1
    -Dproprietary_codecs=1
    -Drelease_extra_cflags="$CFLAGS"
    -Dremove_webcore_debug_symbols=1
    -Dtarget_arch="${_target_arch}"
    -Dusb_ids_path=/usr/share/hwdata/usb.ids
    -Duse_gconf=0
    -Duse_gnome_keyring="${_use_gnome}"
    -Duse_pulseaudio="${_use_pulseaudio}"
    -Dwerror=
    )

  if [ "${_use_clang}" = "1" ]; then
    # -Dclang=1                      |  use clang instead of GCC
    # -Dclang_use_chrome_plugins=0   |  fail if use external clang. only work if use bundled clang (because include own chromium plugin). disable this
    _flags+=(
      -Dclang=1
      -Dclang_use_chrome_plugins=0
      )
    export CC="clang"
    export CXX="clang++"
  elif [ "${_use_clang}" = "0" ]; then
    _flags+=(
      -Dclang=0
    )
  fi

  # TODO
  # -Duse_system_hunspell=1    | upstream changes needed
  # -Duse_system_jsoncpp=1     | need newer jsoncpp (0.6.0-rc2)
  # -Duse_system_libsrtp=1     | https://bugs.gentoo.org/show_bug.cgi?id=459932
  # -Duse_system_libvpx=1      | https://crbug.com/347823
  # -Duse_system_libusb=1      | https://crbug.com/266149
  # -Duse_system_opus=1        | https://code.google.com/p/webrtc/issues/detail?id=3077
  # -Duse_system_protobuf=1    | need update to 2.6.0(?)
  # -Duse_system_sqlite=1      | https://crbug.com/22208
  # -Duse_system_ssl=1         | https://crbug.com/58087
  # -Duse_system_openssl=1     | migrate to boringssl

  local _use_system=(
    -Duse_system_expat=1
    -Duse_system_ffmpeg=0
    -Duse_system_flac=1
    -Duse_system_fontconfig=1
    -Duse_system_harfbuzz=1
    -Duse_system_icu=1
    -Duse_system_jsoncpp=0
    -Duse_system_libevent=0
    -Duse_system_libexif=1
    -Duse_system_libjpeg=1
    -Duse_system_libpng=1
    -Duse_system_libusb=0
    -Duse_system_libvpx=0
    -Duse_system_libwebp=1
    -Duse_system_libxml=1
    -Duse_system_libxnvctrl=0
    -Duse_system_libxslt=1
    -Duse_system_minizip=1
    -Duse_system_nspr=1
    -Duse_system_openssl=0
    -Duse_system_opus=0
    -Duse_system_protobuf=0
    -Duse_system_re2=1
    -Duse_system_snappy=1
    -Duse_system_speex=1
    -Duse_system_sqlite=0
    -Duse_system_ssl=0
    -Duse_system_v8=0
    -Duse_system_yasm=1
    -Duse_system_xdg_utils=1
    -Duse_system_zlib=1
    )

  # Re-configure bundled ffmpeg
  msg2 "Configuring bundled ffmpeg"
  pushd third_party/ffmpeg > /dev/null
  local _build_ffmpeg_args=""
  [ "${CARCH}" = "i686" ] && _build_ffmpeg_args=" --disable-asm"
  chromium/scripts/build_ffmpeg.py linux ${_target_arch} --branding=Chrome -- ${_build_ffmpeg_args}
  chromium/scripts/copy_config.sh
  chromium/scripts/generate_gyp.py
  popd > /dev/null

  msg2 "1337's g0 7h3 p4r7y!"

  # CFLAGS are passed through -Drelease_extra_cflags=
  export -n CFLAGS CXXFLAGS

  build/linux/unbundle/replace_gyp_files.py "${_use_system[@]}"
  build/gyp_chromium --depth=. "${_flags[@]}" "${_use_system[@]}"
  mkdir -p out/Release

  if [ "${_use_pax}" = "1" ]; then
    # Build mksnapshot and pax-mark it.
    ${_CC} ninja -C out/Release -v "mksnapshot"
    paxctl -cm "out/Release/mksnapshot"
  fi

  ${_CC} ninja -C out/Release -v chrome chrome_sandbox chromedriver

  if [ "${_use_pax}" = "1" ]; then
    # Pax-mark again
    paxctl -cm out/Release/chrome
  fi
}

package() {
  install -Dm644 chromium-dev.default "${pkgdir}/etc/chromium-dev/default"
  install -Dm755 chromium-dev.sh "${pkgdir}/usr/bin/chromium-dev"
  install -Dm644 chromium-dev.desktop "${pkgdir}/usr/share/applications/chromium-dev.desktop"
  install -Dm644 "chromium-${pkgver}/LICENSE" "${pkgdir}/usr/share/licenses/chromium-dev/LICENSE"

  cd "chromium-${pkgver}/out/Release"
  install -Dm755 chrome "${pkgdir}/usr/lib/chromium-dev/chromium-dev"
  install -Dm4755 -o root -g root chrome_sandbox "${pkgdir}/usr/lib/chromium-dev/chrome-sandbox"
  install -Dm755 chromedriver "${pkgdir}/usr/lib/chromium-dev/chromedriver"
  ln -s /usr/lib/chromium-dev/chromedriver "${pkgdir}/usr/bin/chromedriver-dev"
  install -Dm644 chrome_100_percent.pak "${pkgdir}/usr/lib/chromium-dev/chrome_100_percent.pak"
  install -Dm644 content_resources.pak "${pkgdir}/usr/lib/chromium-dev/content_resources.pak"
  install -Dm644 keyboard_resources.pak "${pkgdir}/usr/lib/chromium-dev/keyboard_resources.pak"
  install -Dm644 resources.pak "${pkgdir}/usr/lib/chromium-dev/resources.pak"
  install -Dm755 libffmpegsumo.so "${pkgdir}/usr/lib/chromium-dev/libffmpegsumo.so"
  install -Dm755 libpdf.so "${pkgdir}/usr/lib/chromium-dev/libpdf.so"
  find locales -type f -name "*.pak" -exec install -Dm644 '{}' "${pkgdir}/usr/lib/chromium-dev/{}" \;
  install -Dm644 chrome.1 "${pkgdir}/usr/share/man/man1/chromium-dev.1"

  for _size in 16 22 24 32 48 128 256; do
    case "${_size}" in
      16|32) _branding="${srcdir}/chromium-${pkgver}/chrome/app/theme/default_100_percent/chromium" ;;
      *) _branding="${srcdir}/chromium-${pkgver}/chrome/app/theme/chromium" ;;
    esac
    install -Dm644 "${_branding}/product_logo_${_size}.png" "${pkgdir}/usr/share/icons/hicolor/${_size}x${_size}/apps/chromium-dev.png"
  done

  install -Dm755 nacl_helper "${pkgdir}/usr/lib/chromium-dev/nacl_helper"
  install -Dm755 nacl_helper_bootstrap "${pkgdir}/usr/lib/chromium-dev/nacl_helper_bootstrap"
  install -Dm755 nacl_helper_nonsfi "${pkgdir}/usr/lib/chromium-dev/nacl_helper_nonsfi"
  install -Dm755 "nacl_irt_${_arch}.nexe" "${pkgdir}/usr/lib/chromium-dev/nacl_irt_${_arch}.nexe"

  [ "${_use_gnome}" = "1" ] && install -Dm644 "${srcdir}/chromium-dev.xml" "${pkgdir}/usr/share/gnome-control-center/default-apps/chromium-dev.xml"

  # Manually strip binaries so that 'nacl_irt_*.nexe' is left intact
  strip $STRIP_BINARIES "${pkgdir}/usr/lib/chromium-dev/"{chromium-dev,chrome-sandbox,chromedriver,nacl_helper{,_bootstrap,_nonsfi}}
  strip $STRIP_SHARED "${pkgdir}/usr/lib/chromium-dev/"lib{ffmpegsumo,pdf}.so
}
